package com.aiyige.page.learn;

import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.aiyige.BuildConfig;
import com.aiyige.R;
import com.aiyige.arouter.config.ARouterConfig;
import com.aiyige.base.BaseFragment;
import com.aiyige.base.api.ApiManager;
import com.aiyige.base.api.ResponseCode;
import com.aiyige.base.eventbus.EventRefreshLearnPageBanner;
import com.aiyige.base.eventbus.EventSelectInterest;
import com.aiyige.base.eventbus.EventSelectRegion;
import com.aiyige.base.eventbus.EventTapBottomItemRefresh;
import com.aiyige.page.learn.adapter.LearnViewPagerAdapter;
import com.aiyige.page.selectinterest.util.InterestUtil;
import com.aiyige.setup.model.Setup;
import com.aiyige.setup.util.SetupUtil;
import com.aiyige.utils.DummyDataUtil;
import com.aiyige.utils.ErrorUtil;
import com.aiyige.utils.ListUtil;
import com.aiyige.utils.RetrofitUtil;
import com.aiyige.utils.ToastX;
import com.aiyige.utils.banner.Banner;
import com.aiyige.utils.banner.BannerAdapter;
import com.alibaba.android.arouter.launcher.ARouter;
import com.alibaba.fastjson.JSON;
import com.flyco.tablayout.SlidingTabLayout;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.LinkedList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class LearnPage extends BaseFragment {
    @BindView(R.id.tabLayout)
    SlidingTabLayout tabLayout;
    @BindView(R.id.mainVp)
    ViewPager mainVp;
    Unbinder unbinder;
    @BindView(R.id.banner)
    Banner banner;
    @BindView(R.id.bannerIndicatorRv)
    RecyclerView bannerIndicatorRv;
    BannerAdapter bannerAdapter;
    @BindView(R.id.interestTv)
    TextView interestTv;
    IntentFilter intentFilter;
    LearnViewPagerAdapter learnViewPagerAdapter;

    public LearnPage() {

    }

    public static LearnPage newInstance() {
        LearnPage fragment = new LearnPage();
        fragment.setAutoRegisterEventBus(true);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(final LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.page_learn, container, false);
        unbinder = ButterKnife.bind(this, view);
        learnViewPagerAdapter = new LearnViewPagerAdapter(getChildFragmentManager());
        mainVp.setAdapter(learnViewPagerAdapter);
        mainVp.setOffscreenPageLimit(mainVp.getAdapter().getCount());
        tabLayout.setViewPager(mainVp);
        bannerAdapter = new BannerAdapter(getChildFragmentManager());
        bannerAdapter.setupWithBanner(banner);
        bannerAdapter.setupWithIndicator(bannerIndicatorRv);
        bannerAdapter.setData(DummyDataUtil.generateDummyBannerData());
        return view;
    }


    public void requestData() {
        List<String> industryIdList = InterestUtil.getIndustryId();
        ApiManager.getService()
                .getSetup(SetupUtil.GROUP_TYPE_STUDY_SLIDE, BuildConfig.appVersion, ListUtil.isEmpty(industryIdList) ? "" : industryIdList.get(0))
                .enqueue(new Callback<ResponseBody>() {
                    @Override
                    public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                        try {
                            if (response.code() != ResponseCode.OK) {
                                throw new Exception(ErrorUtil.extractMessageFromErrorResponse(response));
                            }
                            String json = RetrofitUtil.getResponseBodyAsString(response);
                            List<Setup> setupList = JSON.parseArray(json, Setup.class);
                            List<BannerAdapter.Data> bannerAdapterDataList = new LinkedList<>();
                            for (Setup setup : setupList) {
                                BannerAdapter.Data bannerAdapterData = new BannerAdapter.Data();
                                bannerAdapterData.setId(setup.getId());
                                bannerAdapterData.setTitle((String) setup.getData().get("title"));
                                bannerAdapterData.setActivityId(0);
                                bannerAdapterData.setUrl((String) setup.getData().get("url"));
                                bannerAdapterData.setLink("");
                                bannerAdapterData.setRouter((String) setup.getData().get("router"));
                                bannerAdapterData.setType(0);
                                bannerAdapterData.setOwner("");
                                bannerAdapterData.setOrderMe(0);
                                bannerAdapterData.setStatus(0);
                                bannerAdapterData.setCreateTime(0);
                                bannerAdapterData.setUpdateTime("");
                                bannerAdapterDataList.add(bannerAdapterData);
                                bannerAdapterData = new BannerAdapter.Data();
                                bannerAdapterData.setId(setup.getId());
                                bannerAdapterData.setTitle((String) setup.getData().get("title"));
                                bannerAdapterData.setActivityId(0);
                                bannerAdapterData.setUrl((String) setup.getData().get("url"));
                                bannerAdapterData.setLink("");
                                bannerAdapterData.setRouter((String) setup.getData().get("router"));
                                bannerAdapterData.setType(0);
                                bannerAdapterData.setOwner("");
                                bannerAdapterData.setOrderMe(0);
                                bannerAdapterData.setStatus(0);
                                bannerAdapterData.setCreateTime(0);
                                bannerAdapterData.setUpdateTime("");
                                bannerAdapterDataList.add(bannerAdapterData);
                            }
                            bannerAdapter.setData(bannerAdapterDataList);
                        } catch (Exception e) {
                            onFailure(call, e);
                        }
                    }

                    @Override
                    public void onFailure(Call<ResponseBody> call, Throwable t) {
                        ToastX.show(t.getMessage());
                    }
                });
    }

    @Override
    public void onDestroyView() {
        bannerAdapter.destory();
        super.onDestroyView();
        unbinder.unbind();
    }

    @Override
    protected void initData() {
        updateInterestTitle();
        requestData();
    }

    @OnClick({R.id.interestLayout, R.id.scanBtn, R.id.searchBar})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.scanBtn:
                ARouter.getInstance()
                        .build(ARouterConfig.ScanQRCodePage)
                        .navigation(getActivity());
                break;
            case R.id.searchBar:
                ARouter.getInstance()
                        .build(ARouterConfig.GlobalSearchPage)
                        .navigation();
                break;
            case R.id.interestLayout:
                ARouter.getInstance()
                        .build(ARouterConfig.SelectInterestPage)
                        .withTransition(R.anim.activity_slide_in_bottom, R.anim.activity_still)
                        .navigation(getActivity());
                break;
        }
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventSelectInterest(EventSelectInterest event) {
        updateInterestTitle();
        requestData();
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventRefreshLearnPageBanner(EventRefreshLearnPageBanner event) {
        requestData();
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(EventSelectRegion event) {
        requestData();
    }

    public void updateInterestTitle() {
        List<String> selectedInterestNameList = InterestUtil.getInterestName();
        if (!ListUtil.isEmpty(selectedInterestNameList)) {
            StringBuffer stringBuffer = new StringBuffer();
            for (int i = 0; i < selectedInterestNameList.size() - 1; ++i) {
                stringBuffer.append(selectedInterestNameList.get(i));
                stringBuffer.append("·");
            }
            stringBuffer.append(selectedInterestNameList.get(selectedInterestNameList.size() - 1));
            interestTv.setText(stringBuffer.toString());
        } else {
            interestTv.setText(R.string.aiyige);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(EventTapBottomItemRefresh event) {
        if (isVisible()
                && event.getItemType() == EventTapBottomItemRefresh.ITEM_TYPE_FIND
                && event.getActionType() == EventTapBottomItemRefresh.ACTION_TYPE_PRE_REFRESH) {
            EventBus.getDefault().post(EventTapBottomItemRefresh.newBuilder()
                    .itemType(EventTapBottomItemRefresh.ITEM_TYPE_FIND)
                    .actionType(EventTapBottomItemRefresh.ACTION_TYPE_START_REFRESH)
                    .pageType(learnViewPagerAdapter.getPage(mainVp.getCurrentItem()).getSubjectIndex())
                    .build());
        }
    }

}
